<script setup lang="ts">
import { ref, watch, onMounted, onBeforeUnmount } from 'vue'

const props = defineProps<{
  open: boolean
  title: string
  icon?: string
}>()
const emit = defineEmits<{
  (e: 'close'): void
}>()

const maximized = ref(false)

function toggleMaximize() {
  maximized.value = !maximized.value
}

function onKeydown(e: KeyboardEvent) {
  if (e.key === 'Escape') emit('close')
}

watch(() => props.open, (val) => {
  if (val) document.body.classList.add('overflow-hidden')
  else document.body.classList.remove('overflow-hidden')
})

onMounted(() => document.addEventListener('keydown', onKeydown))
onBeforeUnmount(() => document.removeEventListener('keydown', onKeydown))
</script>

<template>
  <div v-if="open" class="fixed inset-0 z-50 flex items-center justify-center">
    <!-- overlay -->
    <div class="absolute inset-0 bg-black/50 backdrop-blur-sm animate-fade-in" @click="emit('close')"></div>

    <!-- container -->
    <div
      class="relative w-full modal-animation bg-white dark:bg-gray-800 rounded-lg shadow-2xl overflow-hidden"
      :class="maximized ? 'max-w-[95vw] max-h-[95vh]' : 'max-w-4xl max-h-[90vh]'"
    >
      <!-- header -->
      <div class="flex items-center justify-between px-6 py-4 bg-gray-50 dark:bg-gray-900 border-b border-gray-200 dark:border-gray-700">
        <div class="flex items-center space-x-3">
          <i :class="['fa', icon || 'fa-cog', 'text-primary', 'text-xl']"></i>
          <h2 class="text-lg font-semibold text-gray-900 dark:text-gray-100">{{ title }}</h2>
        </div>
        <div class="flex items-center space-x-2">
          <button class="p-2 rounded hover:bg-gray-200 dark:hover:bg-gray-700 text-gray-600 dark:text-gray-300" @click="toggleMaximize">
            <i class="fa" :class="maximized ? 'fa-compress' : 'fa-expand'"></i>
          </button>
          <button class="p-2 rounded hover:bg-gray-200 dark:hover:bg-gray-700 text-gray-600 dark:text-gray-300" @click="emit('close')">
            <i class="fa fa-times"></i>
          </button>
        </div>
      </div>

      <!-- content -->
      <div class="p-6 overflow-y-auto bg-white dark:bg-gray-800 text-gray-900 dark:text-gray-100" :class="maximized ? 'max-h-[calc(95vh-120px)]' : 'max-h-[calc(90vh-120px)]'">
        <slot />
      </div>

      <!-- footer -->
      <div class="px-6 py-4 bg-gray-50 dark:bg-gray-900 border-t border-gray-200 dark:border-gray-700 flex justify-end">
        <button class="px-4 py-2 bg-primary text-white rounded-lg hover:bg-primary/90" @click="emit('close')">关闭</button>
      </div>
    </div>
  </div>
  
</template>

<style scoped></style>